<template>
  <el-drawer v-model="visibleDrawer" :destroy-on-close="true" :with-header="false" size="50%">
    <el-form>
      <!-- 教师名称 -->
      <el-form-item label="教师名称:">
        <el-input style="width:387px !important" v-model="formTeacher.nickName" placeholder="请输入教师名称"></el-input>
      </el-form-item>

      <!-- 性别 -->
      <el-form-item label="性&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;别:">
        <el-radio-group v-model="formTeacher.sex">
          <el-radio :value="1">男</el-radio>
          <el-radio :value="0">女</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 教师头衔 -->
      <el-form-item label="教师头衔:">
        <el-input style="width:300px !important" v-model="formTeacher.title" placeholder="请输入教师头衔"></el-input>
      </el-form-item>

      <!-- 手机号码 -->
      <el-form-item label="手机号码:">
        <el-input style="width:300px !important" v-model="formTeacher.phone" placeholder="请输入手机号码"></el-input>
      </el-form-item>

      <!-- 电子邮箱 -->
      <el-form-item label="电子邮箱:">
        <el-input style="width:300px !important" v-model="formTeacher.email" placeholder="请输入电子邮箱"></el-input>
      </el-form-item>

      <!-- 设置密码和确认密码 -->
      <el-form-item :label="formTeacher.teacherId ? '重置密码:' : '设置密码:'">
        <el-input style="width:300px !important" v-model="formTeacher.password" type="password"
          placeholder="请输入密码"></el-input>
      </el-form-item>

      <el-form-item label="确认密码:">
        <el-input style="width:300px !important" v-model="formTeacher.confirmPassword" type="password"
          placeholder="请确认密码"></el-input>
      </el-form-item>

      <!-- 身份证号 -->
      <el-form-item label="身份证号:">
        <el-input style="width:387px !important" v-model="formTeacher.identificationCard"
          placeholder="请输入身份证号"></el-input>
      </el-form-item>

      <!-- 入职日期 -->
      <el-form-item label="入职日期:">
        <el-date-picker style="width:387px !important" v-model="formTeacher.hireDate" type="date" placeholder="请选择入职日期"
          format="YYYY-MM-DD"></el-date-picker>
      </el-form-item>

      <!-- 出生日期 -->
      <el-form-item label="出生日期:">
        <el-date-picker style="width:387px !important" v-model="formTeacher.birthday" type="date" placeholder="请选择出生日期"
          format="YYYY-MM-DD"></el-date-picker>
      </el-form-item>

      <!-- 居住地址 -->
      <el-form-item label="居住地址:">
        <el-input style="width:387px !important" v-model="formTeacher.address" placeholder="请输入居住地址"></el-input>
      </el-form-item>

      <!-- 教师简介 -->
      <el-form-item label="教师简介:">
        <el-input type="textarea" style="width:387px !important" v-model="formTeacher.bio" placeholder="请输入教师简介"
          :rows="4" maxlength="200"></el-input>
      </el-form-item>

      <!-- 提交按钮 -->
      <el-form-item>
        <el-button class="teacher-button" type="primary" plain @click="onSubmit()">发布</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { addTeacherService, editTeacherService,getTeacherDetailService } from '@/apis/teacher'

const visibleDrawer = ref(false)
const formTeacher = reactive({
  nickName: '',
  sex: 1,
  title: '',
  phone: '',
  email: '',
  password: '',
  confirmPassword: '',
  identificationCard: '',
  hireDate: '',
  birthday: '',
  address: '',
  bio: '',
})

async function open(teacherId) {
  visibleDrawer.value = true
  for (const key in formTeacher) {
    if (formTeacher.hasOwnProperty(key)) {
      formTeacher[key] = '';
    }
  }
  if (teacherId) {
    const teacherDetail = await getTeacherDetailService(teacherId)
    Object.assign(formTeacher, teacherDetail.data)
  }
}

defineExpose({
  open
})

function validate() {
  let msg = ''
  // 姓名长度限制 (假设昵称不能超过50个字符)
  if (!formTeacher.nickName || formTeacher.nickName.length > 50) {
    msg = '昵称不能为空且不能超过50个字符'
  }
  // 性别是否符合规定
  else if (formTeacher.sex !== 0 && formTeacher.sex !== 1) {  // 1代表男，0代表女
    msg = '性别必须是"男"或"女"'
  }
  // title只能有汉字
  else if (!/^[\u4e00-\u9fa5]+$/.test(formTeacher.title)) {
    msg = '教师头衔只能包含汉字'
  }
  // 手机号码格式
  else if (!/^1[3-9]\d{9}$/.test(formTeacher.phone)) {
    msg = '请输入有效的手机号码'
  }
  // 电子邮箱格式
  else if (!/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/.test(formTeacher.email)) {
    msg = '请输入有效的电子邮箱'
  }
  // 身份证号格式（假设要求是18位）
  else if (!/^\d{17}(\d|X|x)$/.test(formTeacher.identificationCard)) {
    msg = '请输入有效的身份证号码'
  }
  // 入职日期格式（假设格式为YYYY-MM-DD）
  else if (!/^\d{4}-\d{2}-\d{2}$/.test(formTeacher.hireDate)) {
    msg = '入职日期格式无效，正确格式为YYYY-MM-DD'
  }
  // 生日格式（假设格式为YYYY-MM-DD）
  else if (!/^\d{4}-\d{2}-\d{2}$/.test(formTeacher.birthday)) {
    msg = '生日格式无效，正确格式为YYYY-MM-DD'
  }
  // 身份证号与生日对应关系校验（假设身份证号的生日在第7到第14位）
  else if (formTeacher.identificationCard && formTeacher.birthday) {
    const idCardBirth = formTeacher.identificationCard.slice(6, 14); // 获取身份证中的出生日期
    const formattedBirthDate = formTeacher.birthday.replace(/-/g, ''); // 格式化输入的生日
    if (idCardBirth !== formattedBirthDate) {
      msg = '身份证号与生日不一致'
    }
  }
  // 地址长度限制（假设地址不能超过100个字符）
  else if (!formTeacher.address || formTeacher.address.length > 100) {
    msg = '地址不能为空且不能超过100个字符'
  }
  // 简介长度限制（假设简介不能超过200个字符）
  else if (!formTeacher.bio || formTeacher.bio.length > 200) {
    msg = '简介不能超过200个字符'
  }
  else {
    msg = ''
  }
  return msg
}

const emit = defineEmits(['success'])
async function onSubmit() {
  // 修复日期时区问题
  let formattedBirthday = '';
  let formattedHireDate = '';
  
  if (formTeacher.birthday) {
    const date = new Date(formTeacher.birthday);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    formattedBirthday = `${year}-${month}-${day}`;
  }
  
  if (formTeacher.hireDate) {
    const date = new Date(formTeacher.hireDate);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    formattedHireDate = `${year}-${month}-${day}`;
  }
  
  formTeacher.birthday = formattedBirthday;
  formTeacher.hireDate = formattedHireDate;
  
  const errorMessage = '';
  // const errorMessage = validate()
  if (errorMessage) {
    ElMessage.error(errorMessage);
    return false
  }
  const fd = new FormData()
  for (let key in formTeacher) {
    fd.append(key, formTeacher[key])
  }
  console.log(formTeacher)
  if (formTeacher.teacherId) {
    //编辑题目请求
    await editTeacherService(fd)
    ElMessage.success('编辑成功')
    emit('success', 'edit')
  } else {
    await addTeacherService(fd)
    ElMessage.success('添加成功')
    emit('success', 'add')
  }
  visibleDrawer.value = false
}
</script>

<style lang="scss">
.teacher-button {
  width: 200px;
}
</style>